package com.situ.service.impl;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.situ.dao.UserDao;
import com.situ.entily.User;
import com.situ.service.UserService;
import com.situ.util.StringUtil;
import com.situ.vo.ResultVO;

public class UserServiceImpl implements UserService {

	UserDao dao=new UserDao();
	
	@Override
	public Boolean check(String username, String password,HttpSession session) {
//		session.setAttribute("captcha", );
		List<User> u = dao.selectByUsernmae(username);
		Boolean b= u.size()>0&&u.get(0).getUserPassword().equals(StringUtil.md5(password));
		if(b) {
			session.setAttribute("currentUser", u.get(0));
		}
		return b;
	}

	@Override
	public List<User> all(Integer page, Integer limit, String keyword) {
		return dao.all((page - 1) * limit, limit, keyword);
	}

	@Override
	public Long count(String keyword) {
		return dao.count(keyword);
	}

	@Override
	public ResultVO selectById1(Integer id) {
		ResultVO vo=new ResultVO();
		User u=dao.selectById(id);
		if (u == null) {
		    vo.setCode(1);
			vo.setMsg("该用户不存在，请刷新再试");
		}else {
		    vo.setData(u);
		}
		return vo;
	}

	public User selectById(Integer id){
		return dao.selectById(id);
	}
	@Override
	public ResultVO save(User u, HttpSession session, HttpServletRequest request, HttpServletResponse response) {
		ResultVO vo=new ResultVO();
		if (u.getUserId() == null) {//新增
			if(StringUtil.isNotBlank(u.getUserName())){
				vo.setCode(1);
				vo.setMsg("用户名不能为空");
				return vo;
			}
			if(StringUtil.isNotBlank(u.getUserPassword())){
				vo.setCode(1);
				vo.setMsg("密码不能为空");
				return vo;
			}
			List<User> user =dao.selectByUsernmae(u.getUserName());
			if(user.size()>0){
				vo.setCode(1);
				vo.setMsg("用户名已被使用，请更换！");
				return vo;
			}
			u.setUserPassword(StringUtil.md5(u.getUserPassword()));
			vo.setMsg("新增用户成功");
			dao.insert(u);
		} else {
			Object obj=session.getAttribute("currentUser");
			User user=(User) obj;
			u.setUserPassword(StringUtil.md5(u.getUserPassword()));
			if(user.getUserName().equals(u.getUserName()) || user.getUserName().equals("admin")){
				List<User> list =dao.selectByUsernmae(u.getUserName(),u.getUserId());

				if(list.size()>0){
					vo.setCode(1);
					vo.setMsg("用户名已被使用，请更换！");
					return vo;
				}
				dao.update(u);
				if (!user.getUserName().equals("admin")||u.getUserName().equals("admin")){
					vo.setMsg("编辑成功，请刷新重新登录");
					request.getSession().removeAttribute("currentUser");
				}else {
					vo.setMsg("编辑成功");
				}
				//response.sendRedirect("/login");
				return vo;
			}else {
				vo.setCode(1);
				vo.setMsg("您不是超级管理员，不能修改他人信息");
				return vo;
			}
		}
		return vo;
	}
	@Override
	public void delete(Integer id) {
		dao.delete(id);	
	}
	
}
